import {PlusOutlined} from '@ant-design/icons'
import {Modal, Upload, message} from 'antd'
import type {RcFile, UploadProps} from 'antd/es/upload'
import type {UploadFile} from 'antd/es/upload/interface'
import React, {useState} from 'react'
import {uploadFileUrl} from '@/service/common/upload'

const getBase64 = (file: RcFile): Promise<string> =>
	new Promise((resolve, reject) => {
		const reader = new FileReader()
		reader.readAsDataURL(file)
		reader.onload = () => resolve(reader.result as string)
		reader.onerror = (error) => reject(error)
	})

type PropsType = {
	key?: string
	accept: string
	text?: string
	modelName?: string
	targetAttr?: number
	moreNum: number
	callback: {(key: string): void; (arg0: any): void}
}
const customUpload = (props: PropsType) => {
	const {text, modelName, targetAttr, moreNum, accept, callback} = props
	const [previewOpen, setPreviewOpen] = useState(false)
	const [previewImage, setPreviewImage] = useState('')
	const [previewTitle, setPreviewTitle] = useState('')
	const [fileList, setFileList] = useState<UploadFile[]>([])

	const handleCancel = () => setPreviewOpen(false)

	const beforeUpload = (file: RcFile) => {
		const isJpgOrPng = accept.includes(file.type)
		// file.type === 'image/jpeg' || file.type === 'image/png';
		if (!isJpgOrPng) {
			message.error('你只能上传JPG/PNG文件')
		}
		const isLt2M = file.size / 1024 / 1024 < 200
		if (!isLt2M) {
			message.error('文件大小不能大于200M')
		}
		return isJpgOrPng && isLt2M
	}

	const handlePreview = async (file: UploadFile) => {
		if (!file.url && !file.preview) {
			// eslint-disable-next-line no-param-reassign
			file.preview = await getBase64(file.originFileObj as RcFile)
		}

		setPreviewImage(file.url || (file.preview as string))
		setPreviewOpen(true)
		setPreviewTitle(
			file.name || file.url!.substring(file.url!.lastIndexOf('/') + 1),
		)
	}

	const handleChange: UploadProps['onChange'] = ({fileList: newFileList}) => {
		setFileList(newFileList)
		callback(newFileList)
	}

	const uploadButton = (
		<div>
			<PlusOutlined />
			<div style={{marginTop: 8}}>{text}</div>
		</div>
	)
	return (
		<>
			<Upload
				action={uploadFileUrl}
				listType="picture-card"
				fileList={fileList}
				key={modelName}
				data={{
					modelName,
					targetAttr,
					targetId: '1111',
				}}
				beforeUpload={beforeUpload}
				onPreview={handlePreview}
				onChange={handleChange}>
				{fileList.length >= moreNum ? null : uploadButton}
			</Upload>
			<Modal
				open={previewOpen}
				title={previewTitle}
				footer={null}
				onCancel={handleCancel}>
				<img alt="example" style={{width: '100%'}} src={previewImage} />
			</Modal>
		</>
	)
}

export default customUpload
